import { FC, useState } from "react"
import Taro, { useRouter } from '@tarojs/taro'
import { AtImagePicker } from 'taro-ui'
import style from './style.less'

const Receipt: FC = () => {
  const [isShow, setIsShow] = useState(true)
  const [count, setCount] = useState(9)
  const [images, setImages] = useState<any[]>([])

  const router = useRouter()
  const orderNumber = router.params.orderNumber
  const addr = router.params.addr
  const addr2 = router.params.addr2

  const changeFile = (files) => {
    if (files.length === 9) {
      setIsShow(false)
    } else {
      setIsShow(true)
    }
    setCount(9 - files.length)
    setImages(files)
  }

  const submit = () => {
    if (count === 9) {
      Taro.showToast({
        title: '请上传至少一张照片',
        icon: 'none',
        duration: 1500
      })
      return
    }
    Taro.showLoading({ title: '加载中' })
    Taro.request({
      url: 'http://139.9.123.88:8083/fta-trade/order/driver/unloadOrder',
      method: 'POST',
      data: JSON.stringify({
        orderNumber: orderNumber,
        openId: Taro.getStorageSync('token')
      }),
      success: () => {
        Taro.hideLoading()
        Taro.reLaunch({ url: '/pages/order/index' })
      },
      fail: () => {
        Taro.hideLoading()
        console.log('上传照片失败');

      }
    })
  }

  return (
    <div className={style.root}>
      <div className="tips">请上传目的地卸货照片，请保证图片清晰</div>
      <div className="address">
        <div className="start"><i>装</i> {addr}</div>
        <div className="end"><i>卸</i> {addr2}</div>
      </div>
      <AtImagePicker
        count={count}
        length={3}
        multiple
        showAddBtn={isShow}
        files={images}
        onChange={changeFile}
        onFail={(err) => { console.log(err); }}
      />
      <div className="btn" onClick={submit}>
        <div>提交照片</div>
        <div>（最多上传9张）</div>
      </div>
    </div>
  )
}

export default Receipt